package com.web.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * databaseutil类，一个数据库工具类，负责打开和关闭数据库连接
 *
 * @author 12270
 */
public class DatabaseUtil {

    private static final String DRIVER_CLASS;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;
    private static final ResourceBundle rb = ResourceBundle.getBundle("com.web.util.dbconfig");
    
    static{
    DRIVER_CLASS = rb.getString("jdbc.driverClass");
    URL = rb.getString("jdbc.url");
    USERNAME = rb.getString("jdbc.username");
    PASSWORD = rb.getString("jdbc.password");
    }
    
    /**
     * 打开一个数据库连接
     * @return 一个connection对象，表示一个数据库连接
     */
    public static Connection getConnection(){
        
        Connection con = null;
        
        try {
            Class.forName(DRIVER_CLASS);
            con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return con;
    }
    
    /**
     * 关闭用到的数据库连接/结果集/语句
     * @param rs 需要关闭的resultset对象
     * @param stmt 需要关闭的statement对象
     * @param con 需要关闭的connection对象
     */
    public static void close(ResultSet rs,Statement stmt,Connection con){
        
            try {
                if(null!=rs){
                rs.close();
                }
                if(null!=stmt){
                stmt.close();
                }
                if(null!=con){
                con.close();
                }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        
    }
}
